﻿<%@ WebHandler Language="C#" Class="Thumbnail" %>

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;
using System.Net;

public class Thumbnail : IHttpHandler {
    private Regex _nameValidationExpression = new Regex(@"[^\w/]");
    private int _WthumbnailSize;
    private int _HthumbnailSize;
    private string RequestImage;
    
    
    public void ProcessRequest(HttpContext context) 
    {
        GetParameters();
        
        //string photoName = context.Request.QueryString["p"];
        //if (_nameValidationExpression.IsMatch(photoName)) {
        //    throw new HttpException(404, "Invalid photo name.");
        //}
        string photoName = RequestImage.Split('/')[RequestImage.Split('/').Length - 2]+RequestImage.Split('.')[RequestImage.Split('.').Length - 1]; 
        string cachePath = Path.Combine(HttpRuntime.CodegenDir, photoName.Remove(photoName.Length - 4) + ".square.png");
        if (File.Exists(cachePath)&&!RequestImage.Contains("http"))
        {
            OutputCacheResponse(context, File.GetLastWriteTime(cachePath));
            context.Response.WriteFile(cachePath);
            return;
        }
        
        string photoPath = context.Server.MapPath("~/gallery/" + photoName);

        StreamReader sr = null;
        HttpWebResponse webResponseObject = null;
        HttpWebRequest webRequestObject = null;
        Bitmap photo;
        try
        {
            webRequestObject = (HttpWebRequest)WebRequest.Create(RequestImage);
            webRequestObject.Method = "GET";

            webResponseObject = (HttpWebResponse)webRequestObject.GetResponse();
            sr = new StreamReader(webResponseObject.GetResponseStream());
            
            photo = new Bitmap(sr.BaseStream);
        }
        catch (ArgumentException) {
            throw new HttpException(404, "Photo not found.");
        }
        finally
        {
            try
            {
                sr.Close();
                webResponseObject.Close();
                webRequestObject.Abort();
            }
            catch { }
        }
        context.Response.ContentType = "image/png";
        int width, height;
        width = _WthumbnailSize;
        height =_HthumbnailSize;
        Bitmap target = new Bitmap(_WthumbnailSize, _HthumbnailSize);
        using (Graphics graphics = Graphics.FromImage(target)) {
            graphics.CompositingQuality = CompositingQuality.HighSpeed;
            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphics.CompositingMode = CompositingMode.SourceCopy;
            graphics.DrawImage(photo, (_WthumbnailSize - width) / 2, (_HthumbnailSize - height) / 2, width, height);
            using (MemoryStream memoryStream = new MemoryStream()) {
                target.Save(memoryStream, ImageFormat.Png);
                OutputCacheResponse(context, File.GetLastWriteTime(photoPath));
                    using (FileStream diskCacheStream = new FileStream(cachePath, FileMode.CreateNew))
                    {
                        memoryStream.WriteTo(diskCacheStream);
                    }

                memoryStream.WriteTo(context.Response.OutputStream);
            }
        }
    }
    
    private void GetParameters()
    {
        RequestImage = HttpContext.Current.Request.QueryString["Img"];
        _WthumbnailSize = Convert.ToInt32((HttpContext.Current.Request.QueryString["sizeW"]));
        _HthumbnailSize = Convert.ToInt32((HttpContext.Current.Request.QueryString["sizeH"]));
    }

    private static void OutputCacheResponse(HttpContext context, DateTime lastModified)
    {

        HttpCachePolicy cachePolicy = context.Response.Cache;
        cachePolicy.SetCacheability(HttpCacheability.Public);
        cachePolicy.VaryByParams["Img"] = true;
        cachePolicy.SetOmitVaryStar(true);
        cachePolicy.SetExpires(DateTime.Now + TimeSpan.FromDays(7));
        cachePolicy.SetValidUntilExpires(true);
        cachePolicy.SetLastModified(lastModified);

    }
 
    public bool IsReusable {
        get {
            return true;
        }
    }
}